#include "fileinfotab.h"
#include <QHeaderView>
#include <QVBoxLayout>
#include <QApplication>
#include <QClipboard>
#include <QFile>
#include <QTextStream>
#include <QFileDialog>
#include <QMessageBox>
#include "infoprint/infoprint.h"

FileInfoTab::FileInfoTab(QWidget *parent)
    : QWidget{parent}
    , m_pTable{nullptr}
    , m_contextMenu{nullptr}
    , m_copyAction{nullptr}
    , m_copyRowAction{nullptr}
    , m_copyAllAction{nullptr}
    , m_exportAction{nullptr}
    , m_data{std::make_unique<FileInfoData>()}
{
    initUI();
    initContextMenu();
    logMessage("FileInfoTab已创建");
}

FileInfoTab::~FileInfoTab()
{
    logMessage("FileInfoTab已销毁");
}

void FileInfoTab::initUI()
{
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(5, 5, 5, 5);
    
    m_pTable = new QTableWidget(17, 2, this);
    
    // 自定义表格的尺寸和字体大小
    m_pTable->resize(1180, 600);
    
    // 设置表格中每一行的表头
    m_pTable->setHorizontalHeaderLabels(QStringList() << "名称" << "值");
    
    // 设置表格数据区内的所有单元格都不允许编辑
    m_pTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    
    // 设置表格外观
    m_pTable->horizontalHeader()->setFixedHeight(45);
    m_pTable->horizontalHeader()->setStyleSheet("QHeaderView::section{background:skyblue;}");
    m_pTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    m_pTable->verticalHeader()->setVisible(false);
    m_pTable->setAlternatingRowColors(true);
    m_pTable->setStyleSheet("QTableWidget{alternate-background-color: #f7f7f7;}");
    
    // 启用右键菜单
    m_pTable->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(m_pTable, &QTableWidget::customContextMenuRequested, this, &FileInfoTab::onCustomContextMenu);

    QString tabHeadText[] = {
        QObject::tr("FileLen(文件长度)"),
        QObject::tr("Version(规范版本号)"),
        QObject::tr("CreateDate(文件生成时间)"),
        QObject::tr("StationName(站点名称)"),
        QObject::tr("StationNum(站点编码)"),
        QObject::tr("Weather(天气)"),
        QObject::tr("Temperature(温度)"),
        QObject::tr("Humidity(湿度)"),
        QObject::tr("DeviceCompany(仪器厂家)"),
        QObject::tr("DeviceModel(仪器型号)"),
        QObject::tr("DeviceVersion(仪器版本号)"),
        QObject::tr("SerialNumber(仪器序列号)"),
        QObject::tr("Frequency(系统频率)"),
        QObject::tr("ChatNumber(图谱数量)"),
        QObject::tr("Longitude(经度)"),
        QObject::tr("Latitude(纬度值)"),
        QObject::tr("Altitude(海拔)"),
    };
    
    for(int i = 0; i < 17; i++) {
        m_pTable->setItem(i, 0, createTableWidgetItem(tabHeadText[i]));
    }
    
    mainLayout->addWidget(m_pTable);
    setLayout(mainLayout);
    
    // 初始化数据结构
    m_data->fileLength = 0;
    m_data->version = "";
    m_data->createDate = "";
    m_data->stationName = "";
    m_data->stationNum = "";
    m_data->weather = DataSpecificationGW::WEATHER_UNRECORD;
    m_data->temperature = 0.0f;
    m_data->humidity = 0;
    m_data->deviceCompany = "";
    m_data->deviceModel = "";
    m_data->deviceVersion = "";
    m_data->serialNumber = "";
    m_data->frequency = 0;
    m_data->chartNumber = 0;
    m_data->longitude = 0.0;
    m_data->latitude = 0.0;
    m_data->altitude = 0;
}

void FileInfoTab::initContextMenu()
{
    m_contextMenu = new QMenu(this);
    
    m_copyAction = new QAction("复制选中内容", this);
    connect(m_copyAction, &QAction::triggered, this, &FileInfoTab::copySelectedCells);
    m_contextMenu->addAction(m_copyAction);
    
    m_copyRowAction = new QAction("复制整行", this);
    connect(m_copyRowAction, &QAction::triggered, this, &FileInfoTab::copyRow);
    m_contextMenu->addAction(m_copyRowAction);
    
    m_copyAllAction = new QAction("复制所有内容", this);
    connect(m_copyAllAction, &QAction::triggered, this, &FileInfoTab::copyAllData);
    m_contextMenu->addAction(m_copyAllAction);
    
    m_contextMenu->addSeparator();
    
    m_exportAction = new QAction("导出数据...", this);
    connect(m_exportAction, &QAction::triggered, [this]() {
        QString filePath = QFileDialog::getSaveFileName(this, 
                                                      "导出文件信息", 
                                                      QString(), 
                                                      "CSV文件 (*.csv);;文本文件 (*.txt);;所有文件 (*.*)");
        if (!filePath.isEmpty()) {
            if (exportToFile(filePath)) {
                QMessageBox::information(this, "成功", "数据导出成功");
                logMessage(QString("文件信息已导出到 %1").arg(filePath));
            } else {
                QMessageBox::warning(this, "错误", "数据导出失败");
                logMessage(QString("导出文件信息到 %1 失败").arg(filePath));
            }
        }
    });
    m_contextMenu->addAction(m_exportAction);
}

void FileInfoTab::onCustomContextMenu(const QPoint& pos)
{
    if (m_contextMenu) {
        m_contextMenu->exec(m_pTable->mapToGlobal(pos));
    }
}

void FileInfoTab::copySelectedCells()
{
    QList<QTableWidgetItem*> selectedItems = m_pTable->selectedItems();
    if (selectedItems.isEmpty()) {
        return;
    }
    
    QString text;
    for (const auto& item : selectedItems) {
        text += item->text() + "\t";
    }
    
    QApplication::clipboard()->setText(text);
    logMessage("已复制选中内容到剪贴板");
}

void FileInfoTab::copyRow()
{
    QList<QTableWidgetItem*> selectedItems = m_pTable->selectedItems();
    if (selectedItems.isEmpty()) {
        return;
    }
    
    // 获取选中行
    int row = selectedItems.first()->row();
    
    QTableWidgetItem* nameItem = m_pTable->item(row, 0);
    QTableWidgetItem* valueItem = m_pTable->item(row, 1);
    
    if (nameItem && valueItem) {
        QString text = nameItem->text() + "\t" + valueItem->text();
        QApplication::clipboard()->setText(text);
        logMessage(QString("已复制行 %1 内容到剪贴板").arg(row + 1));
    }
}

void FileInfoTab::copyAllData()
{
    QString text;
    
    // 添加表头
    text += m_pTable->horizontalHeaderItem(0)->text() + "\t";
    text += m_pTable->horizontalHeaderItem(1)->text() + "\n";
    
    // 添加内容
    for (int row = 0; row < m_pTable->rowCount(); ++row) {
        QTableWidgetItem* nameItem = m_pTable->item(row, 0);
        QTableWidgetItem* valueItem = m_pTable->item(row, 1);
        
        if (nameItem && valueItem) {
            text += nameItem->text() + "\t" + valueItem->text() + "\n";
        }
    }
    
    QApplication::clipboard()->setText(text);
    logMessage("已复制所有内容到剪贴板");
}

bool FileInfoTab::exportToFile(const QString& filePath)
{
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        return false;
    }
    
    QTextStream out(&file);
    
    // 写入表头
    out << m_pTable->horizontalHeaderItem(0)->text() << ",";
    out << m_pTable->horizontalHeaderItem(1)->text() << "\n";
    
    // 写入内容
    for (int row = 0; row < m_pTable->rowCount(); ++row) {
        QTableWidgetItem* nameItem = m_pTable->item(row, 0);
        QTableWidgetItem* valueItem = m_pTable->item(row, 1);
        
        if (nameItem && valueItem) {
            out << "\"" << nameItem->text() << "\",";
            out << "\"" << valueItem->text() << "\"\n";
        }
    }
    
    file.close();
    return true;
}

void FileInfoTab::clearTable()
{
    // 清空表格内容，但保留表头
    for (int row = 0; row < m_pTable->rowCount(); ++row) {
        QTableWidgetItem* item = m_pTable->item(row, 1);
        if (item) {
            item->setText("");
        }
    }
    
    // 重置数据结构
    m_data->fileLength = 0;
    m_data->version = "";
    m_data->createDate = "";
    m_data->stationName = "";
    m_data->stationNum = "";
    m_data->weather = DataSpecificationGW::WEATHER_UNRECORD;
    m_data->temperature = 0.0f;
    m_data->humidity = 0;
    m_data->deviceCompany = "";
    m_data->deviceModel = "";
    m_data->deviceVersion = "";
    m_data->serialNumber = "";
    m_data->frequency = 0;
    m_data->chartNumber = 0;
    m_data->longitude = 0.0;
    m_data->latitude = 0.0;
    m_data->altitude = 0;
    
    logMessage("表格数据已清空");
}

QString FileInfoTab::getSummary() const
{
    if (!m_data) {
        return "无数据";
    }
    
    QString summary = QString("文件信息摘要：\n")
            + QString("站点: %1 (%2)\n").arg(m_data->stationName).arg(m_data->stationNum)
            + QString("生成时间: %1\n").arg(m_data->createDate)
            + QString("文件长度: %1\n").arg(m_data->fileLength)
            + QString("图谱数量: %1\n").arg(m_data->chartNumber)
            + QString("仪器信息: %1 %2").arg(m_data->deviceCompany).arg(m_data->deviceModel);
    
    return summary;
}

void FileInfoTab::logMessage(const QString& message)
{
    InfoLogPrint(QString("FileInfoTab: %1").arg(message));
}

// 修改和增强原有的setter方法实现

void FileInfoTab::setFileLen(qint32 length)
{
    m_data->fileLength = length;
    
    QTableWidgetItem *itemValue = new QTableWidgetItem();
    itemValue->setTextAlignment(Qt::AlignCenter);
    itemValue->setText(QString::number(length));
    m_pTable->setItem(0, 1, itemValue);
    
    logMessage(QString("设置文件长度: %1").arg(length));
}

void FileInfoTab::setVersion(const QString& dataFileVersion)
{
    m_data->version = dataFileVersion;
    
    QTableWidgetItem *item = new QTableWidgetItem();
    item->setTextAlignment(Qt::AlignCenter);
    item->setText(dataFileVersion);
    m_pTable->setItem(1, 1, item);
    
    logMessage(QString("设置规范版本号: %1").arg(dataFileVersion));
}

void FileInfoTab::setCreateDate(const QString &date)
{
    m_data->createDate = date;
    
    // 尝试格式化日期显示
    QString formattedDate = date;
    if (date.length() == 17) {
        // "YYYYMMDDhhmmssfff" 格式
        formattedDate = date.mid(0, 4) + "-" + date.mid(4, 2) + "-" + date.mid(6, 2) + " " +
                        date.mid(8, 2) + ":" + date.mid(10, 2) + ":" + date.mid(12, 2);
    }
    
    QTableWidgetItem *itemValue = new QTableWidgetItem();
    itemValue->setTextAlignment(Qt::AlignCenter);
    itemValue->setText(formattedDate);
    m_pTable->setItem(2, 1, itemValue);
    
    logMessage(QString("设置文件生成时间: %1").arg(formattedDate));
}

void FileInfoTab::setStationName(const QString &name)
{
    m_data->stationName = name;
    
    QTableWidgetItem *itemValue = new QTableWidgetItem();
    itemValue->setTextAlignment(Qt::AlignCenter);
    itemValue->setText(name);
    m_pTable->setItem(3, 1, itemValue);
    
    logMessage(QString("设置站点名称: %1").arg(name));
}

void FileInfoTab::setStationNum(const QString& no)
{
    m_data->stationNum = no;
    
    QTableWidgetItem *itemValue = new QTableWidgetItem();
    itemValue->setTextAlignment(Qt::AlignCenter);
    itemValue->setText(no);
    m_pTable->setItem(4, 1, itemValue);
    
    logMessage(QString("设置站点编码: %1").arg(no));
}

void FileInfoTab::setWeather(DataSpecificationGW::Weather eWeather)
{
    m_data->weather = eWeather;
    
    QTableWidgetItem *itemValue = new QTableWidgetItem();
    itemValue->setTextAlignment(Qt::AlignCenter);
    
    QString weatherText;
    switch (eWeather) {
    case DataSpecificationGW::WEATHER_UNRECORD://未记录
        weatherText = "未记录";
        break;
    case DataSpecificationGW::WEATHER_SUNSHINE://晴：
        weatherText = "晴";
        itemValue->setForeground(QColor(255, 165, 0)); // 橙色表示晴天
        break;
    case DataSpecificationGW::WEATHER_OVERCAST://阴
        weatherText = "阴";
        itemValue->setForeground(QColor(128, 128, 128)); // 灰色表示阴天
        break;
    case DataSpecificationGW::WEATHER_RAINY://雨
        weatherText = "雨";
        itemValue->setForeground(QColor(30, 144, 255)); // 蓝色表示雨天
        break;
    case DataSpecificationGW::WEATHER_SNOWY://雪：
        weatherText = "雪";
        itemValue->setForeground(QColor(240, 248, 255)); // 淡蓝色表示雪天
        break;
    case DataSpecificationGW::WEATHER_FOG://雾：
        weatherText = "雾";
        itemValue->setForeground(QColor(220, 220, 220)); // 淡灰色表示雾天
        break;
    case DataSpecificationGW::WEATHER_THUNDERSTORM://雷雨
        weatherText = "雷雨";
        itemValue->setForeground(QColor(138, 43, 226)); // 紫色表示雷雨
        break;
    case DataSpecificationGW::WEATHER_CLOUDY://多云：
        weatherText = "多云";
        itemValue->setForeground(QColor(70, 130, 180)); // 钢青色表示多云
        break;
    default:
        weatherText = "未知";
        break;
    }
    
    itemValue->setText(weatherText);
    m_pTable->setItem(5, 1, itemValue);
    
    logMessage(QString("设置天气: %1").arg(weatherText));
}

void FileInfoTab::setTemperature(float temperature)
{
    m_data->temperature = temperature;
    
    QTableWidgetItem *itemValue = new QTableWidgetItem();
    itemValue->setTextAlignment(Qt::AlignCenter);
    itemValue->setText(QString::number(temperature) + " °C");
    
    // 根据温度设置不同颜色
    if (temperature < 0) {
        itemValue->setForeground(QColor(0, 191, 255)); // 低温蓝色
    } else if (temperature > 35) {
        itemValue->setForeground(QColor(255, 69, 0)); // 高温橙红色
    }
    
    m_pTable->setItem(6, 1, itemValue);
    
    logMessage(QString("设置温度: %1 °C").arg(temperature));
}

void FileInfoTab::setHumidity(int humidity)
{
    m_data->humidity = humidity;
    
    QTableWidgetItem *itemValue = new QTableWidgetItem();
    itemValue->setTextAlignment(Qt::AlignCenter);
    itemValue->setText(QString::number(humidity) + " %");
    
    // 合法性检查
    if (humidity < 0 || humidity > 100) {
        itemValue->setForeground(QColor(255, 0, 0)); // 错误值显示红色
    }
    
    m_pTable->setItem(7, 1, itemValue);
    
    logMessage(QString("设置湿度: %1 %").arg(humidity));
}

void FileInfoTab::setDeviceCompany(const QString &deviceCompany)
{
    m_data->deviceCompany = deviceCompany;
    
    QTableWidgetItem *itemValue = new QTableWidgetItem();
    itemValue->setTextAlignment(Qt::AlignCenter);
    itemValue->setText(deviceCompany);
    m_pTable->setItem(8, 1, itemValue);
    
    logMessage(QString("设置仪器厂家: %1").arg(deviceCompany));
}

void FileInfoTab::setDeviceModel(const QString &deviceModel)
{
    m_data->deviceModel = deviceModel;
    
    QTableWidgetItem *itemValue = new QTableWidgetItem();
    itemValue->setTextAlignment(Qt::AlignCenter);
    itemValue->setText(deviceModel);
    m_pTable->setItem(9, 1, itemValue);
    
    logMessage(QString("设置仪器型号: %1").arg(deviceModel));
}

void FileInfoTab::setDeviceVersion(const QString& qstrInstrumentVersion)
{
    m_data->deviceVersion = qstrInstrumentVersion;
    
    QTableWidgetItem *itemValue = new QTableWidgetItem();
    itemValue->setTextAlignment(Qt::AlignCenter);
    itemValue->setText(qstrInstrumentVersion);
    m_pTable->setItem(10, 1, itemValue);
    
    logMessage(QString("设置仪器版本号: %1").arg(qstrInstrumentVersion));
}

void FileInfoTab::setSerialNumber(const QString &serialNumber)
{
    m_data->serialNumber = serialNumber;
    
    QTableWidgetItem *itemValue = new QTableWidgetItem();
    itemValue->setTextAlignment(Qt::AlignCenter);
    itemValue->setText(serialNumber);
    m_pTable->setItem(11, 1, itemValue);
    
    logMessage(QString("设置仪器序列号: %1").arg(serialNumber));
}

void FileInfoTab::setFrequency(int frequency)
{
    m_data->frequency = frequency;
    
    QTableWidgetItem *itemValue = new QTableWidgetItem();
    itemValue->setTextAlignment(Qt::AlignCenter);
    itemValue->setText(QString::number(frequency) + " Hz");
    m_pTable->setItem(12, 1, itemValue);
    
    logMessage(QString("设置系统频率: %1 Hz").arg(frequency));
}

void FileInfoTab::setChatNumber(int chatNum)
{
    m_data->chartNumber = chatNum;
    
    QTableWidgetItem *itemValue = new QTableWidgetItem();
    itemValue->setTextAlignment(Qt::AlignCenter);
    itemValue->setText(QString::number(chatNum));
    
    // 如果没有图谱，显示红色
    if (chatNum == 0) {
        itemValue->setForeground(QColor(255, 0, 0));
    }
    
    m_pTable->setItem(13, 1, itemValue);
    
    logMessage(QString("设置图谱数量: %1").arg(chatNum));
}

void FileInfoTab::setLongitude(double longitude)
{
    m_data->longitude = longitude;
    
    QTableWidgetItem *itemValue = new QTableWidgetItem();
    itemValue->setTextAlignment(Qt::AlignCenter);
    
    // 格式化显示经度
    QString formattedText;
    if (longitude >= 0) {
        formattedText = QString::number(longitude, 'f', 6) + " E"; // 东经
    } else {
        formattedText = QString::number(-longitude, 'f', 6) + " W"; // 西经
    }
    
    itemValue->setText(formattedText);
    
    // 经度合法性检查 (-180 ~ 180)
    if (longitude < -180 || longitude > 180) {
        itemValue->setForeground(QColor(255, 0, 0));
    }
    
    m_pTable->setItem(14, 1, itemValue);
    
    logMessage(QString("设置经度: %1").arg(formattedText));
}

void FileInfoTab::setLatitude(double latitude)
{
    m_data->latitude = latitude;
    
    QTableWidgetItem *itemValue = new QTableWidgetItem();
    itemValue->setTextAlignment(Qt::AlignCenter);
    
    // 格式化显示纬度
    QString formattedText;
    if (latitude >= 0) {
        formattedText = QString::number(latitude, 'f', 6) + " N"; // 北纬
    } else {
        formattedText = QString::number(-latitude, 'f', 6) + " S"; // 南纬
    }
    
    itemValue->setText(formattedText);
    
    // 纬度合法性检查 (-90 ~ 90)
    if (latitude < -90 || latitude > 90) {
        itemValue->setForeground(QColor(255, 0, 0));
    }
    
    m_pTable->setItem(15, 1, itemValue);
    
    logMessage(QString("设置纬度: %1").arg(formattedText));
}

void FileInfoTab::setAltitude(int altitude)
{
    m_data->altitude = altitude;
    
    QTableWidgetItem *itemValue = new QTableWidgetItem();
    itemValue->setTextAlignment(Qt::AlignCenter);
    itemValue->setText(QString::number(altitude) + " m");
    m_pTable->setItem(16, 1, itemValue);
    
    logMessage(QString("设置海拔: %1 m").arg(altitude));
}

QTableWidgetItem *FileInfoTab::createTableWidgetItem(const QString &text)
{
    QTableWidgetItem *item = new QTableWidgetItem();
    QFont font;
    font.setBold(true);
    item->setFont(font);
    item->setTextAlignment(Qt::AlignCenter);
    item->setText(text);
    return item;
}
